using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.Diagnostics;
namespace TeamDeploy.Tasks
{
    public class KillProcess : TaskBase
    {
        public override bool Execute()
        {
            try
            {
                if (!System.IO.File.Exists(KillAppPathFilename))
                {
                    Log.LogError("KillApp does not exists at: " + KillAppPathFilename);
                    return false;
                }

                string args = "\\\\" + TargetMachine + " -accepteula " + ProcessName;
                Process p = Process.Start(KillAppPathFilename, args);
                p.WaitForExit();

                if (p.ExitCode != 0)
                {
                    string message = "Process " + ProcessName + " on " + TargetMachine + " returned code:" + p.ExitCode;

                    if (ignoreExitCode)
                    {
                        Log.LogMessage(message);
                    }
                    else
                    {
                        Log.LogError(message);
                        return false;
                    }
                }
                if (BuildEngine != null)
                {
                    Log.LogMessage("Process " + ProcessName + " on " + TargetMachine + " had been terminated.");
                }
                return true;

            }
            catch (Exception ex)
            {
                if (BuildEngine != null)
                {
                    Log.LogError("Error executing KillProcess: ProcessName=" + ProcessName + " TargetMachine=" +
                                 TargetMachine + " KillPathFilename=" + KillAppPathFilename + ":::" + ex);
                }
                return false;
            }
        }


        [Required]
        public string ProcessName { get; set; }

        [Required]
        public string TargetMachine { get; set; }

        [Required]
        public string KillAppPathFilename { get; set; }
    }

}
